package com.atguigu.gmall.common.util;

import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.util.ClassUtils;

import java.io.IOException;

/**
 * @author: 李旭
 * @create: 2021-08-25 14:08
 **/
public class FastDFSUtils {

    static {
        //获取配置文件的路径
        String path = ClassUtils.getDefaultClassLoader().
                getResource("fdfs_client.conf").getPath();
        try {
            ClientGlobal.init(path);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //上传图片
    public static String uploadFile(byte[] file,String originalFilename){
        //1:客户端连接跟踪器
        TrackerClient trackerClient = new TrackerClient();
        //2:获取存储节点的IP：PORT
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getConnection();
            //3:连接存储节点
            StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);
            //4:获取扩展名
            String ext = FilenameUtils.getExtension(originalFilename);
            //5:上传图片
            String fileId = storageClient1.upload_file1(
                    file, ext, null);
            //6:返回文件ID
            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //下载图片

}
